dojo.require("dojo.io.script");
dojo.require("dojo.cookie");
//var server = "http://localhost:8080/ECS_Server/"
var commenter = {
    currentUserName: "guest",
    currentRepliedId: -1,
    addReplyHandler: null,
    addCommentHandler: null,
    addUserClick: function(name){
        var url = server + "addUser.jsp?n=" + name;
        dojo.io.script.get({
            url: url,
            callbackParamName: "callback",
            handle: this._handleAddUser
        })
    },
    _handleAddUser: function(feedBack){
        dojo.cookie("userId", feedBack.userId, {});
        hideAddUserForm();
        commenter.currentUserName = dojo.byId("userName").value;
        var option = new Option(commenter.currentUserName, feedBack.userId);
        dojo.byId("userSelector").add(option, dojo.byId("userSelector").options[0]);
        dojo.byId('userName').value = "";
        dojo.byId("userSelector").selectedIndex = 0;
    },
    getUser: function(userId){
        if (userId == "undefined") 
            return;
        var url = server + "getUser.jsp?id=" + userId;
        dojo.io.script.get({
            url: url,
            callbackParamName: "callback",
            handle: this._handleGetUser
        })
    },
    _handleGetUser: function(feedBack){
        commenter.currentUserName = feedBack.name;
        var option = new Option(commenter.currentUserName, dojo.cookie("userId"));
        dojo.byId("userSelector").add(option, dojo.byId("userSelector").options[0]);
        dojo.byId('userName').value = "";
        dojo.byId("userSelector").selectedIndex = 0;
    },
    addCommentClick: function(){
        var comment = encodeURIComponent(dojo.byId("comment").value);
        var userId = dojo.cookie("userId");
        var pageUrl = encodeURIComponent(window.location);
        var title = encodeURIComponent(commenter._format(document.getElementsByTagName("title")[0].innerHTML));
        var url = server + "addComment.jsp?url=" + pageUrl + "&content=" + comment + "&userId=" + userId + "&title=" + title;
        dojo.io.script.get({
            url: url,
            callbackParamName: "callback",
            handle: commenter._handleAddComment
        })
    },
    _handleAddComment: function(feedBack){
        var commentId = feedBack.commentId;
        var comment = dojo.byId("comment").value;
        dojo.byId("comment").value = "";
        hideCreateCommentForm();
        dojo.style(dojo.byId("commentListContainer"), "display", "block");
        commenter._newComment(commentId, comment, commenter.currentUserName);
    },
    _newComment: function(commentId, commentText, userName){
        var comment = dojo.clone(dojo.byId("commentTemplate").childNodes[0 ]);
        dojo.attr(comment, "id", "comment_" + commentId);
        dojo.attr(comment, "commentDepth", 0);
        dojo.attr(comment, "replyTo", 0);
        dojo.addClass(comment, "replyTo_0");
        
        dojo.byId("commentList").appendChild(comment);
        if (dojo.byId("commentList").childNodes.length > 1) {
            var divider = dojo.clone(dojo.byId("commentDivider"));
            dojo.style(divider, "display", "block");
            dojo.place(divider, dojo.byId("comment_" + commentId), "first");
        }
        commenter._renderComment(commentId, commentText, userName);
    },
    _renderComment: function(commentId, commentText, userName){
        dojo.query(".js-singleCommentName", dojo.byId("comment_" + commentId))[0].innerHTML = userName;
        dojo.query(".commentText", dojo.byId("comment_" + commentId))[0].innerHTML = commentText;
        //add event to "reply" button
        var replyButton = dojo.query(".js-singleCommentReply", dojo.byId("comment_" + commentId))[0];
        dojo.attr(replyButton, "commentId", commentId);
    },
    showReplyForm: function(e){
        showCreateCommentForm();
        commenter.currentRepliedId = dojo.attr(e.currentTarget, "commentId");
        var submitCommentButton = dojo.byId("submitComment");
        dojo.disconnect(commenter.addCommentHandler);
        commenter.addReplyHandler = dojo.connect(submitCommentButton, "onclick", null, commenter._addReplyClick);
    },
    _addReplyClick: function(e){
        var submitCommentButton = dojo.byId("submitComment");
        dojo.disconnect(commenter.addReplyHandler)
        dojo.connect(submitCommentButton, "onclick", null, commenter.addCommentClick);
        var comment = encodeURIComponent(commenter._format(dojo.byId("comment").value));
        var userId = dojo.cookie("userId");
        var url = server + "addReply.jsp?content=" + comment + "&commentId=" + commenter.currentRepliedId + "&userId=" + userId;
        dojo.io.script.get({
            url: url,
            callbackParamName: "callback",
            handle: commenter._handleAddReply
        })
    },
    _handleAddReply: function(feedBack){
        var replyId = feedBack.replyId;
        var comment = dojo.byId("comment").value;
        dojo.byId("comment").value = "";
        hideCreateCommentForm();
        commenter._newReply(replyId, comment, commenter.currentRepliedId, commenter.currentUserName);
        var reply = dojo.byId("comment_" + replyId);
        dojo.query(".words", reply)[0].innerHTML = "replies:"
    },
    _newReply: function(replyId, commentText, repliedId, userName){
        var repliedComment = dojo.byId("comment_" + repliedId);
        var depth = dojo.attr(repliedComment, "commentDepth");
        var parentReplyTo = dojo.attr(repliedComment, "replyTo");
        var reply = dojo.clone(dojo.byId("commentTemplate").childNodes[0]);
        
        depth = depth * 1 + 1;
        dojo.attr(reply, "id", "comment_" + replyId);
        dojo.attr(reply, "commentDepth", depth);
        dojo.addClass(reply, "replyTo_" + repliedId);
        dojo.attr(reply, "replyTo", repliedId);
        
        var allComments = dojo.query(".js-singleComment");
        var position = dojo.indexOf(allComments, repliedComment) +
        commenter._getThreadSize(repliedId);
        var previousComment = allComments[position];
        dojo.place(reply, previousComment, "after");
        dojo.byId("comment_" + replyId).style.marginLeft = depth * 10 + "px";
        commenter._renderComment(replyId, commentText, userName);
    },
    _getThreadSize: function(commentId){
        var threads = dojo.query(".replyTo_" + commentId);
        var count = threads.length;
        for (var i = 0; i < threads.length; i++) {
            var thread = threads[i];
            var threadId = dojo.attr(thread, "id");
            count += this._getThreadSize(threadId.split('_')[1]);
        }
        return count;
    },
    render: function(){
        var url = server + "getComments.jsp?url=" + escape(window.location);
        dojo.io.script.get({
            url: url,
            callbackParamName: "callback",
            handle: commenter._handleRenderComments
        })
    },
    _handleRenderComments: function(feedBack){
        var comments = feedBack;
        if (comments.length > 0) {
            dojo.style("commentListContainer", "display", "block");
        }
        for (var i = 0; i < comments.length; i++) {
            commenter._populateSingleComment(comments[i]);
        }
    },
    _populateSingleComment: function(data){
        var commentId = data.id;
        var commentText = unescape(data.comment);
        var userName = data.userName;
        commenter._newComment(commentId, commentText, userName);
        var replies = data.replies;
        for (var i = 0; i < replies.length; i++) {
            commenter._populateReply(replies[i], commentId);
        }
    },
    _populateReply: function(data, repliedId){
        var replyId = data.id;
        var commentText = unescape(data.comment);
        var userName = data.userName;
        var replies = data.replies;
        this._newReply(replyId, commentText, repliedId, userName);
        var reply = dojo.byId("comment_" + replyId);
        dojo.query(".words", reply)[0].innerHTML = "replies:"
        for (var i = 0; i < replies.length; i++) {
            commenter._populateReply(replies[i], replyId);
        }
    },
	_format:function(p){
		return p.replace(/\r|\n|\r\n/g,"");
	}
}
function showCreateCommentForm(){
    dojo.style("leaveComment", "display", "none");
    dojo.style("createCommentForm", "display", "block");
    dojo.byId("comment").focus();
    commenter.addCommentHandler = dojo.connect(dojo.byId("submitComment"), "onclick", null, commenter.addCommentClick);
}

function hideCreateCommentForm(){
    dojo.style("leaveComment", "display", "block");
    dojo.style("createCommentForm", "display", "none");
}

function showAddUserForm(){
    dojo.style("createCommentForm", "opacity", 0.5);
    dojo.style("addUserForm", "display", "block");
    dojo.byId("userName").focus();
}

function hideAddUserForm(){
    dojo.style("createCommentForm", "opacity", 1);
    dojo.style("addUserForm", "display", "none");
}

function modifyUserId(){
    var item = dojo.byId("userSelector").options[dojo.byId("userSelector").selectedIndex];
    commenter.currentUserName = item.text;
    dojo.cookie("userId", item.value);
}


var userId = dojo.cookie("userId");
if (userId != "undefined")
    commenter.getUser(userId);
commenter.render();

